---
title: "OpenTelemetry Bridge | Tracing | Observability"
description: "Integrate Mastra tracing with existing OpenTelemetry infrastructure"
---

# OpenTelemetry Bridge

:::warning

The OpenTelemetry Bridge is currently **experimental**. APIs and configuration options may change in future releases.

:::

The OpenTelemetry (OTEL) Bridge enables bidirectional integration between Mastra's tracing system and existing OpenTelemetry infrastructure. Unlike exporters that send trace data to external platforms, the bridge creates native OTEL spans that participate in your distributed tracing context.

:::info Looking to send traces without existing OTEL infrastructure?

If you don't have existing OpenTelemetry instrumentation, the [OpenTelemetry Exporter](/docs/v1/observability/tracing/exporters/otel) may be simpler — it sends traces directly without requiring an OTEL SDK setup.

:::

## When to Use the Bridge

Use the OtelBridge when you:

- Have existing OTEL instrumentation in your application (HTTP servers, database clients, etc.)
- Want Mastra operations to appear as child spans of your existing OTEL traces
- Need OTEL-instrumented code inside Mastra tools to maintain proper parent-child relationships
- Are building a distributed system where trace context must propagate across services

## How It Works

The OtelBridge provides two-way integration:

**From OTEL to Mastra:**
- Reads from OTEL ambient context (AsyncLocalStorage) automatically
- Inherits trace ID and parent span ID from active OTEL spans
- Respects OTEL sampling decisions — if a trace is not sampled, Mastra won't create spans for it
- No manual trace ID passing required when OTEL auto-instrumentation is active

**From Mastra to OTEL:**
- Creates native OTEL spans for Mastra operations (agents, LLM calls, tools, workflows)
- Maintains proper parent-child relationships in distributed traces
- Allows OTEL-instrumented code (HTTP clients, database calls) within Mastra operations to nest correctly

## Installation

```bash npm2yarn
npm install @mastra/otel-bridge
```

The bridge works with your existing OpenTelemetry setup. Depending on your configuration, you may also need some of these packages:

- `@opentelemetry/sdk-node` - Core Node.js SDK for OTEL
- `@opentelemetry/auto-instrumentations-node` - Auto-instrumentation for common libraries
- `@opentelemetry/exporter-trace-otlp-proto` - OTLP exporter (Protobuf over HTTP)
- `@opentelemetry/exporter-trace-otlp-http` - OTLP exporter (JSON over HTTP)
- `@opentelemetry/exporter-trace-otlp-grpc` - OTLP exporter (gRPC)
- `@opentelemetry/sdk-trace-base` - Base tracing SDK (for BatchSpanProcessor, etc.)
- `@opentelemetry/core` - Core utilities (for W3CTraceContextPropagator, etc.)

## Configuration

Using the OtelBridge requires two steps:

1. Configure OpenTelemetry instrumentation in your application
2. Add the OtelBridge to your Mastra observability config

### Step 1: OpenTelemetry Instrumentation

Create an instrumentation file that initializes OTEL. This must run before your application code:

```typescript title="instrumentation.ts" showLineNumbers copy
import { NodeSDK } from "@opentelemetry/sdk-node";
import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
import { W3CTraceContextPropagator } from "@opentelemetry/core";

const sdk = new NodeSDK({
  serviceName: "my-service",
  spanProcessors: [
    new BatchSpanProcessor(
      new OTLPTraceExporter({
        url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT || "http://localhost:4318/v1/traces",
      })
    ),
  ],
  instrumentations: [getNodeAutoInstrumentations()],
  textMapPropagator: new W3CTraceContextPropagator(),
});

sdk.start();

export { sdk };
```

### Step 2: Mastra Configuration

Add the OtelBridge to your Mastra observability config:

```typescript title="src/mastra/index.ts" showLineNumbers copy
import { Mastra } from "@mastra/core";
import { Observability } from "@mastra/observability";
import { OtelBridge } from "@mastra/otel-bridge";

export const mastra = new Mastra({
  observability: new Observability({
    configs: {
      default: {
        serviceName: "my-service",
        bridge: new OtelBridge(),
      },
    },
  }),
  agents: {
    /* your agents */
  },
});
```

No Mastra exporters are required when using the bridge — traces are sent via your OTEL SDK configuration. You can optionally add Mastra exporters if you want to send traces to additional destinations.

### Running Your Application

Use the `--import` flag to ensure instrumentation loads before your application:

```bash
tsx --import ./instrumentation.ts ./src/index.ts
```

## Semantic Conventions

The OtelBridge exports Mastra spans using [OpenTelemetry Semantic Conventions for GenAI v1.38.0](https://github.com/open-telemetry/semantic-conventions/tree/v1.38.0/docs/gen-ai). This includes standardized span names (`chat {model}`, `execute_tool {tool_name}`, etc.) and attributes (`gen_ai.usage.input_tokens`, `gen_ai.request.model`, etc.).

For details on span naming and attributes, see the [OpenTelemetry Exporter semantic conventions](/docs/v1/observability/tracing/exporters/otel#opentelemetry-semantic-conventions).

## Trace Hierarchy

With the OtelBridge, your traces maintain proper hierarchy across OTEL and Mastra boundaries:

```
HTTP POST /api/chat (from Hono middleware)
└── agent.assistant (from Mastra via OtelBridge)
    ├── chat gpt-4o (LLM call)
    ├── tool.execute search (tool execution)
    │   └── HTTP GET api.example.com (from OTEL auto-instrumentation)
    └── chat gpt-4o (follow-up LLM call)
```

## Multi-Service Distributed Tracing

The OtelBridge enables trace propagation across service boundaries. When Service A calls Service B via HTTP, trace context propagates automatically:

```
Service A: HTTP POST /api/process
└── HTTP POST service-b/api/analyze (outgoing call)

Service B: HTTP POST /api/analyze (incoming call - same trace!)
└── agent.analyzer (Mastra agent inherits trace context)
    └── chat gpt-4o
```

Both services must have:
1. OTEL instrumentation configured
2. W3C Trace Context propagator enabled
3. Mastra with OtelBridge configured

## Using Tags

Tags help you categorize and filter traces in your OTEL backend. Add tags when executing agents or workflows:

```typescript
const result = await agent.generate({
  messages: [{ role: "user", content: "Hello" }],
  tracingOptions: {
    tags: ["production", "experiment-v2", "user-request"],
  },
});
```

Tags are exported as a JSON string in the `mastra.tags` span attribute for broad backend compatibility. Common use cases include:

- Environment labels: `"production"`, `"staging"`
- Experiment tracking: `"experiment-v1"`, `"control-group"`
- Priority levels: `"priority-high"`, `"batch-job"`

## Troubleshooting

If traces aren't appearing or connecting as expected:

- Verify OTEL SDK is initialized before Mastra (use `--import` flag or import at top of entry point)
- Ensure the OtelBridge is added to your observability config
- Check that your OTEL backend is running and accessible

## Related

- [Tracing Overview](/docs/v1/observability/tracing/overview)
- [OpenTelemetry Exporter](/docs/v1/observability/tracing/exporters/otel) - For sending traces to OTEL backends
- [OtelBridge Reference](/reference/v1/observability/tracing/bridges/otel) - API documentation
